home *** CD-ROM | disk | FTP | other *** search
/ Freelog 100 / FreelogNo100-NovembreDecembre2010.iso / Musique / solfege / solfege-win32-3.17.0.exe / {app} / bin / Lib / encodings / __init__.py next >
Text File  |  2008-02-12  |  6KB  |  155 lines

  1. """ Standard "encodings" Package
  2.  
  3.     Standard Python encoding modules are stored in this package
  4.     directory.
  5.  
  6.     Codec modules must have names corresponding to normalized encoding
  7.     names as defined in the normalize_encoding() function below, e.g.
  8.     'utf-8' must be implemented by the module 'utf_8.py'.
  9.  
  10.     Each codec module must export the following interface:
  11.  
  12.     * getregentry() -> codecs.CodecInfo object
  13.     The getregentry() API must a CodecInfo object with encoder, decoder,
  14.     incrementalencoder, incrementaldecoder, streamwriter and streamreader
  15.     atttributes which adhere to the Python Codec Interface Standard.
  16.  
  17.     In addition, a module may optionally also define the following
  18.     APIs which are then used by the package's codec search function:
  19.  
  20.     * getaliases() -> sequence of encoding name strings to use as aliases
  21.  
  22.     Alias names returned by getaliases() must be normalized encoding
  23.     names as defined by normalize_encoding().
  24.  
  25. Written by Marc-Andre Lemburg (mal@lemburg.com).
  26.  
  27. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  28.  
  29. """#"
  30.  
  31. import codecs, types
  32. from encodings import aliases
  33.  
  34. _cache = {}
  35. _unknown = '--unknown--'
  36. _import_tail = ['*']
  37. _norm_encoding_map = ('                                              . '
  38.                       '0123456789       ABCDEFGHIJKLMNOPQRSTUVWXYZ     '
  39.                       ' abcdefghijklmnopqrstuvwxyz                     '
  40.                       '                                                '
  41.                       '                                                '
  42.                       '                ')
  43. _aliases = aliases.aliases
  44.  
  45. class CodecRegistryError(LookupError, SystemError):
  46.     pass
  47.  
  48. def normalize_encoding(encoding):
  49.  
  50.     """ Normalize an encoding name.
  51.  
  52.         Normalization works as follows: all non-alphanumeric
  53.         characters except the dot used for Python package names are
  54.         collapsed and replaced with a single underscore, e.g. '  -;#'
  55.         becomes '_'. Leading and trailing underscores are removed.
  56.  
  57.         Note that encoding names should be ASCII only; if they do use
  58.         non-ASCII characters, these must be Latin-1 compatible.
  59.  
  60.     """
  61.     # Make sure we have an 8-bit string, because .translate() works
  62.     # differently for Unicode strings.
  63.     if hasattr(types, "UnicodeType") and type(encoding) is types.UnicodeType:
  64.         # Note that .encode('latin-1') does *not* use the codec
  65.         # registry, so this call doesn't recurse. (See unicodeobject.c
  66.         # PyUnicode_AsEncodedString() for details)
  67.         encoding = encoding.encode('latin-1')
  68.     return '_'.join(encoding.translate(_norm_encoding_map).split())
  69.  
  70. def search_function(encoding):
  71.  
  72.     # Cache lookup
  73.     entry = _cache.get(encoding, _unknown)
  74.     if entry is not _unknown:
  75.         return entry
  76.  
  77.     # Import the module:
  78.     #
  79.     # First try to find an alias for the normalized encoding
  80.     # name and lookup the module using the aliased name, then try to
  81.     # lookup the module using the standard import scheme, i.e. first
  82.     # try in the encodings package, then at top-level.
  83.     #
  84.     norm_encoding = normalize_encoding(encoding)
  85.     aliased_encoding = _aliases.get(norm_encoding) or \
  86.                        _aliases.get(norm_encoding.replace('.', '_'))
  87.     if aliased_encoding is not None:
  88.         modnames = [aliased_encoding,
  89.                     norm_encoding]
  90.     else:
  91.         modnames = [norm_encoding]
  92.     for modname in modnames:
  93.         if not modname or '.' in modname:
  94.             continue
  95.         try:
  96.             mod = __import__('encodings.' + modname,
  97.                              globals(), locals(), _import_tail)
  98.         except ImportError:
  99.             pass
  100.         else:
  101.             break
  102.     else:
  103.         mod = None
  104.  
  105.     try:
  106.         getregentry = mod.getregentry
  107.     except AttributeError:
  108.         # Not a codec module
  109.         mod = None
  110.  
  111.     if mod is None:
  112.         # Cache misses
  113.         _cache[encoding] = None
  114.         return None
  115.  
  116.     # Now ask the module for the registry entry
  117.     entry = getregentry()
  118.     if not isinstance(entry, codecs.CodecInfo):
  119.         if not 4 <= len(entry) <= 7:
  120.             raise CodecRegistryError,\
  121.                  'module "%s" (%s) failed to register' % \
  122.                   (mod.__name__, mod.__file__)
  123.         if not callable(entry[0]) or \
  124.            not callable(entry[1]) or \
  125.            (entry[2] is not None and not callable(entry[2])) or \
  126.            (entry[3] is not None and not callable(entry[3])) or \
  127.            (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \
  128.            (len(entry) > 5 and entry[5] is not None and not callable(entry[5])):
  129.             raise CodecRegistryError,\
  130.                 'incompatible codecs in module "%s" (%s)' % \
  131.                 (mod.__name__, mod.__file__)
  132.         if len(entry)<7 or entry[6] is None:
  133.             entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],)
  134.         entry = codecs.CodecInfo(*entry)
  135.  
  136.     # Cache the codec registry entry
  137.     _cache[encoding] = entry
  138.  
  139.     # Register its aliases (without overwriting previously registered
  140.     # aliases)
  141.     try:
  142.         codecaliases = mod.getaliases()
  143.     except AttributeError:
  144.         pass
  145.     else:
  146.         for alias in codecaliases:
  147.             if not _aliases.has_key(alias):
  148.                 _aliases[alias] = modname
  149.  
  150.     # Return the registry entry
  151.     return entry
  152.  
  153. # Register the search_function in the Python codec registry
  154. codecs.register(search_function)
  155.